<template>
  <div id="appEditPage">
    <div class="page-header">
      <div class="header-content">
        <a-button @click="goBack" class="back-btn">
          <template #icon>
            <ArrowLeftOutlined />
          </template>
          返回
        </a-button>
        <div class="header-title">
          <span class="title-icon">✏️</span>
          <h1>编辑应用</h1>
          <div class="title-subtitle">修改应用的基本信息和配置</div>
        </div>
      </div>
    </div>

    <div class="edit-container">
      <a-card :loading="loading" class="info-card">
        <template #title>
          <div class="card-title">
            <span class="card-icon">📝</span>
            <span>基本信息</span>
          </div>
        </template>
        <a-form
          :model="formData"
          :rules="rules"
          layout="vertical"
          @finish="handleSubmit"
          ref="formRef"
          class="edit-form"
        >
          <a-form-item label="应用名称" name="appName" class="form-item">
            <div class="input-wrapper">
              <span class="input-icon">🏷️</span>
              <a-input
                v-model:value="formData.appName"
                placeholder="请输入应用名称"
                :maxlength="50"
                show-count
                class="styled-input"
              />
            </div>
          </a-form-item>

          <a-form-item
            v-if="isAdmin"
            label="应用封面"
            name="cover"
            extra="支持图片链接，建议尺寸：400x300"
            class="form-item"
          >
            <div class="input-wrapper">
              <span class="input-icon">🖼️</span>
              <a-input 
                v-model:value="formData.cover" 
                placeholder="请输入封面图片链接" 
                class="styled-input"
              />
            </div>
            <div v-if="formData.cover" class="cover-preview">
              <div class="preview-label">
                <span class="preview-icon">👁️</span>
                <span>封面预览</span>
              </div>
              <div class="preview-image-container">
                <a-image
                  :src="formData.cover"
                  :width="200"
                  :height="150"
                  fallback=""
                  class="preview-image"
                />
              </div>
            </div>
          </a-form-item>

          <a-form-item v-if="isAdmin" label="优先级" name="priority" extra="设置为99表示精选应用" class="form-item">
            <div class="input-wrapper">
              <span class="input-icon">⭐</span>
              <a-input-number
                v-model:value="formData.priority"
                :min="0"
                :max="99"
                style="width: 200px"
                class="styled-input-number"
              />
            </div>
          </a-form-item>

          <a-form-item label="初始提示词" name="initPrompt" class="form-item">
            <div class="textarea-wrapper">
              <span class="textarea-icon">💬</span>
              <a-textarea
                v-model:value="formData.initPrompt"
                placeholder="请输入初始提示词"
                :rows="4"
                :maxlength="1000"
                show-count
                disabled
                class="styled-textarea"
              />
            </div>
            <div class="form-tip">初始提示词不可修改</div>
          </a-form-item>

          <a-form-item label="生成类型" name="codeGenType" class="form-item">
            <div class="input-wrapper">
              <span class="input-icon">⚙️</span>
              <a-input
                :value="formatCodeGenType(formData.codeGenType)"
                placeholder="生成类型"
                disabled
                class="styled-input"
              />
            </div>
            <div class="form-tip">生成类型不可修改</div>
          </a-form-item>

          <a-form-item v-if="formData.deployKey" label="部署密钥" name="deployKey" class="form-item">
            <div class="input-wrapper">
              <span class="input-icon">🔑</span>
              <a-input 
                v-model:value="formData.deployKey" 
                placeholder="部署密钥" 
                disabled 
                class="styled-input"
              />
            </div>
            <div class="form-tip">部署密钥不可修改</div>
          </a-form-item>

          <a-form-item class="submit-item">
            <div class="submit-wrapper">
              <a-space size="large">
                <a-button 
                  type="primary" 
                  html-type="submit" 
                  :loading="submitting"
                  size="large"
                  class="submit-btn"
                >
                  <template #icon v-if="!submitting">
                    <span>💾</span>
                  </template>
                  {{ submitting ? '保存中...' : '保存修改' }}
                </a-button>
                <a-button @click="resetForm" size="large" class="reset-btn">
                  <template #icon>
                    <span>🔄</span>
                  </template>
                  重置
                </a-button>
                <a-button type="link" @click="goToChat" size="large" class="chat-btn">
                  <template #icon>
                    <span>💬</span>
                  </template>
                  进入对话
                </a-button>
              </a-space>
            </div>
          </a-form-item>
        </a-form>
      </a-card>

      <!-- 应用信息展示 -->
      <a-card title="应用信息" style="margin-top: 24px">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="应用ID">
            {{ appInfo?.id }}
          </a-descriptions-item>
          <a-descriptions-item label="创建者">
            <div class="user-info">
              <a-avatar :src="appInfo?.user?.userAvatar" size="small" />
              <span>{{ appInfo?.user?.userName || '未知用户' }}</span>
            </div>
          </a-descriptions-item>
          <a-descriptions-item label="创建时间">
            {{ formatTime(appInfo?.createTime) }}
          </a-descriptions-item>
          <a-descriptions-item label="更新时间">
            {{ formatTime(appInfo?.updateTime) }}
          </a-descriptions-item>
          <a-descriptions-item label="部署时间">
            {{ appInfo?.deployedTime ? formatTime(appInfo.deployedTime) : '未部署' }}
          </a-descriptions-item>
          <a-descriptions-item label="访问链接">
            <a-button v-if="appInfo?.deployKey" type="link" @click="openPreview" size="small">
              查看预览
            </a-button>
            <span v-else>未部署</span>
          </a-descriptions-item>
        </a-descriptions>
      </a-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { useLoginUserStore } from '@/stores/loginUser'
import { getAppVoById, updateApp, updateAppByAdmin } from '@/api/appController'
import { formatCodeGenType } from '@/utils/codeGenTypes'
import { ArrowLeftOutlined } from '@ant-design/icons-vue'
import dayjs from 'dayjs'
import type { FormInstance } from 'ant-design-vue'
import { getStaticPreviewUrl } from '@/config/env.ts'

const route = useRoute()
const router = useRouter()
const loginUserStore = useLoginUserStore()

// 应用信息
const appInfo = ref<API.AppVO>()
const loading = ref(false)
const submitting = ref(false)
const formRef = ref<FormInstance>()

// 表单数据
const formData = reactive({
  appName: '',
  cover: '',
  priority: 0,
  initPrompt: '',
  codeGenType: '',
  deployKey: '',
})

// 是否为管理员
const isAdmin = computed(() => {
  return loginUserStore.loginUser.userRole === 'admin'
})

// 表单验证规则
const rules = {
  appName: [
    { required: true, message: '请输入应用名称', trigger: 'blur' },
    { min: 1, max: 50, message: '应用名称长度在1-50个字符', trigger: 'blur' },
  ],
  cover: [{ type: 'url', message: '请输入有效的URL', trigger: 'blur' }],
  priority: [{ type: 'number', min: 0, max: 99, message: '优先级范围0-99', trigger: 'blur' }],
}

// 获取应用信息
const fetchAppInfo = async () => {
  const id = route.params.id as string
  if (!id) {
    message.error('应用ID不存在')
    router.push('/')
    return
  }

  loading.value = true
  try {
    const res = await getAppVoById({ id: id as unknown as number })
    if (res.data.code === 0 && res.data.data) {
      appInfo.value = res.data.data

      // 检查权限
      if (!isAdmin.value && appInfo.value.userId !== loginUserStore.loginUser.id) {
        message.error('您没有权限编辑此应用')
        router.push('/')
        return
      }

      // 填充表单数据
      formData.appName = appInfo.value.appName || ''
      formData.cover = appInfo.value.cover || ''
      formData.priority = appInfo.value.priority || 0
      formData.initPrompt = appInfo.value.initPrompt || ''
      formData.codeGenType = appInfo.value.codeGenType || ''
      formData.deployKey = appInfo.value.deployKey || ''
    } else {
      message.error('获取应用信息失败')
      router.push('/')
    }
  } catch (error) {
    console.error('获取应用信息失败：', error)
    message.error('获取应用信息失败')
    router.push('/')
  } finally {
    loading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!appInfo.value?.id) return

  submitting.value = true
  try {
    let res
    if (isAdmin.value) {
      // 管理员可以修改更多字段
      res = await updateAppByAdmin({
        id: appInfo.value.id,
        appName: formData.appName,
        cover: formData.cover,
        priority: formData.priority,
      })
    } else {
      // 普通用户只能修改应用名称
      res = await updateApp({
        id: appInfo.value.id,
        appName: formData.appName,
      })
    }

    if (res.data.code === 0) {
      message.success('修改成功')
      // 重新获取应用信息
      await fetchAppInfo()
    } else {
      message.error('修改失败：' + res.data.message)
    }
  } catch (error) {
    console.error('修改失败：', error)
    message.error('修改失败')
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (appInfo.value) {
    formData.appName = appInfo.value.appName || ''
    formData.cover = appInfo.value.cover || ''
    formData.priority = appInfo.value.priority || 0
  }
  formRef.value?.clearValidate()
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 进入对话页面
const goToChat = () => {
  if (appInfo.value?.id) {
    router.push(`/app/chat/${appInfo.value.id}`)
  }
}

// 打开预览
const openPreview = () => {
  if (appInfo.value?.codeGenType && appInfo.value?.id) {
    // const url = `http://localhost:8123/api/static/${appInfo.value.codeGenType}_${appInfo.value.id}/`
    const url = getStaticPreviewUrl(appInfo.value.codeGenType, String(appInfo.value.id))
    window.open(url, '_blank')
  }
}

// 格式化时间
const formatTime = (time: string | undefined) => {
  if (!time) return ''
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

// 页面加载时获取应用信息
onMounted(() => {
  fetchAppInfo()
})
</script>

<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap');

/* 统一动画变量 */
:root {
  --animation-duration-fast: 0.2s;
  --animation-duration-normal: 0.3s;
  --animation-duration-slow: 0.5s;
  --animation-easing: cubic-bezier(0.4, 0, 0.2, 1);
  --animation-easing-bounce: cubic-bezier(0.68, -0.55, 0.265, 1.55);
}

/* 动画定义 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideInLeft {
  from {
    opacity: 0;
    transform: translateX(-30px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

#appEditPage {
  padding: 32px;
  max-width: 1000px;
  margin: 0 auto;
  background: rgba(248, 250, 252, 0.8);
  min-height: 100vh;
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  animation: fadeInUp 0.8s var(--animation-easing);
}

/* 页面头部样式 */
.page-header {
  margin-bottom: 32px;
  padding: 28px;
  background: rgba(255, 255, 255, 0.98);
  border-radius: 20px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.08);
  animation: slideInLeft 0.6s var(--animation-easing);
  position: relative;
  overflow: hidden;
}

.page-header::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, #8b5cf6 0%, #a855f7 50%, #c084fc 100%);
  border-radius: 20px 20px 0 0;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.back-btn {
  height: 40px;
  padding: 0 16px;
  border-radius: 12px;
  font-weight: 600;
  background: rgba(139, 92, 246, 0.1);
  border: 2px solid rgba(139, 92, 246, 0.2);
  color: #8b5cf6;
  transition: all var(--animation-duration-normal) var(--animation-easing);
}

.back-btn:hover {
  background: rgba(139, 92, 246, 0.15);
  border-color: rgba(139, 92, 246, 0.4);
  transform: translateX(-2px);
  box-shadow: 0 4px 12px rgba(139, 92, 246, 0.2);
}

.header-title {
  flex: 1;
  text-align: center;
}

.title-icon {
  font-size: 28px;
  margin-bottom: 8px;
  display: block;
}

.header-title h1 {
  font-size: 24px;
  font-weight: 700;
  color: #1a202c;
  margin: 0;
  margin-bottom: 4px;
}

.title-subtitle {
  font-size: 14px;
  color: #64748b;
  font-weight: 500;
  opacity: 0.8;
}



:deep(.ant-btn) {
  border-radius: 8px;
  font-weight: 500;
  transition: all var(--animation-duration-normal) var(--animation-easing);
}

:deep(.ant-btn:hover) {
  transform: translateY(-1px);
}

/* 编辑容器样式 */
.edit-container {
  background: rgba(255, 255, 255, 0.98);
  padding: 32px;
  border-radius: 20px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.08);
  animation: fadeInUp 0.6s var(--animation-easing) 0.2s both;
  position: relative;
  overflow: hidden;
}

.edit-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, #06b6d4 0%, #0891b2 50%, #0e7490 100%);
  border-radius: 20px 20px 0 0;
}

.info-card {
  border: none;
  background: transparent;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 18px;
  font-weight: 700;
  color: #1a202c;
}

.card-icon {
  font-size: 20px;
}

.edit-form {
  padding: 8px 0;
}

.form-item {
  margin-bottom: 28px;
}

.input-wrapper,
.textarea-wrapper,
.select-wrapper {
  position: relative;
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.input-icon,
.textarea-icon,
.select-icon {
  font-size: 18px;
  margin-top: 8px;
  color: #64748b;
  flex-shrink: 0;
}

.styled-input,
.styled-textarea,
.styled-select,
.styled-input-number {
  flex: 1;
  border-radius: 12px;
  border: 2px solid rgba(226, 232, 240, 0.8);
  transition: all var(--animation-duration-normal) var(--animation-easing);
  font-weight: 500;
}

.styled-input:hover,
.styled-textarea:hover,
.styled-select:hover,
.styled-input-number:hover {
  border-color: rgba(6, 182, 212, 0.4);
  box-shadow: 0 0 0 3px rgba(6, 182, 212, 0.05);
}

.styled-input:focus,
.styled-textarea:focus,
.styled-select:focus,
.styled-input-number:focus {
  border-color: #06b6d4;
  box-shadow: 0 0 0 3px rgba(6, 182, 212, 0.15);
}

.styled-input {
  height: 40px;
}

.styled-textarea {
  min-height: 100px;
  resize: vertical;
}

.styled-select {
  height: 40px;
}

.styled-input-number {
  height: 40px;
}

:deep(.ant-card) {
  border-radius: 12px;
  border: 1px solid rgba(229, 231, 235, 0.5);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
  transition: all var(--animation-duration-normal) var(--animation-easing);
}

:deep(.ant-card:hover) {
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

:deep(.ant-card-head) {
  background: rgba(102, 126, 234, 0.05);
  border-bottom: 1px solid rgba(102, 126, 234, 0.1);
  border-radius: 12px 12px 0 0;
}

:deep(.ant-card-head-title) {
  font-weight: 600;
  color: #374151;
  font-size: 16px;
}

:deep(.ant-form-item-label > label) {
  font-weight: 600;
  color: #374151;
  transition: all var(--animation-duration-normal) var(--animation-easing);
}

:deep(.ant-form-item:hover .ant-form-item-label > label) {
  color: #667eea;
  transform: translateX(2px);
}

:deep(.ant-input) {
  border-radius: 8px;
  border: 1px solid rgba(209, 213, 219, 0.8);
  transition: all var(--animation-duration-normal) var(--animation-easing);
  font-weight: 500;
}

:deep(.ant-input:hover) {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
}

:deep(.ant-input:focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.15);
}

:deep(.ant-input-number) {
  border-radius: 8px;
  border: 1px solid rgba(209, 213, 219, 0.8);
  transition: all var(--animation-duration-normal) var(--animation-easing);
  font-weight: 500;
}

:deep(.ant-input-number:hover) {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
}

:deep(.ant-input-number:focus-within) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.15);
}

:deep(.ant-btn-primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 8px;
  font-weight: 600;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
  transition: all var(--animation-duration-normal) var(--animation-easing);
}

:deep(.ant-btn-primary:hover) {
  background: linear-gradient(135deg, #5a67d8 0%, #6b46c1 100%);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
  transform: translateY(-2px);
}

/* 封面预览样式 */
.cover-preview {
  margin-top: 20px;
  padding: 20px;
  background: rgba(248, 250, 252, 0.6);
  border-radius: 16px;
  border: 1px solid rgba(226, 232, 240, 0.8);
  animation: fadeInUp 0.4s var(--animation-easing);
}

.preview-label {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 14px;
  font-weight: 600;
  color: #4b5563;
  margin-bottom: 16px;
}

.preview-icon {
  font-size: 16px;
}

.preview-image-container {
  text-align: center;
}

.preview-image {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: transform var(--animation-duration-normal) var(--animation-easing);
}

.preview-image:hover {
  transform: scale(1.02);
}

/* 表单提示样式 */
.form-tip {
  margin-top: 12px;
  padding: 8px 12px;
  font-size: 12px;
  color: #64748b;
  background: rgba(251, 191, 36, 0.1);
  border-radius: 8px;
  border-left: 3px solid #fbbf24;
  font-style: italic;
}

/* 提交区域样式 */
.submit-item {
  margin-top: 40px;
  margin-bottom: 0;
}

.submit-wrapper {
  text-align: center;
  padding: 24px;
  background: rgba(248, 250, 252, 0.6);
  border-radius: 16px;
  border: 1px solid rgba(226, 232, 240, 0.8);
}

.submit-btn {
  height: 48px;
  padding: 0 32px;
  border-radius: 12px;
  font-weight: 700;
  font-size: 16px;
  background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%);
  border: none;
  box-shadow: 0 4px 15px rgba(6, 182, 212, 0.3);
  transition: all var(--animation-duration-normal) var(--animation-easing);
}

.submit-btn:hover {
  background: linear-gradient(135deg, #0891b2 0%, #0e7490 100%);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(6, 182, 212, 0.4);
}

.reset-btn {
  height: 48px;
  padding: 0 24px;
  border-radius: 12px;
  font-weight: 600;
  font-size: 14px;
  background: rgba(107, 114, 128, 0.1);
  border: 2px solid rgba(107, 114, 128, 0.2);
  color: #6b7280;
  transition: all var(--animation-duration-normal) var(--animation-easing);
}

.reset-btn:hover {
  background: rgba(107, 114, 128, 0.15);
  border-color: rgba(107, 114, 128, 0.4);
  transform: translateY(-1px);
}

.chat-btn {
  height: 48px;
  padding: 0 24px;
  border-radius: 12px;
  font-weight: 600;
  font-size: 14px;
  color: #8b5cf6;
  transition: all var(--animation-duration-normal) var(--animation-easing);
}

.chat-btn:hover {
  color: #7c3aed;
  transform: translateY(-1px);
  text-shadow: 0 2px 4px rgba(139, 92, 246, 0.2);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 12px;
  background: rgba(102, 126, 234, 0.05);
  border-radius: 8px;
  transition: all var(--animation-duration-normal) var(--animation-easing);
}

.user-info:hover {
  background: rgba(102, 126, 234, 0.1);
  transform: translateX(2px);
}

:deep(.ant-descriptions-item-label) {
  background: rgba(102, 126, 234, 0.05);
  font-weight: 600;
  color: #374151;
  border-radius: 6px;
  padding: 8px 12px;
}

:deep(.ant-descriptions-item-content) {
  font-weight: 500;
  color: #4b5563;
}

/* 响应式设计 */
@media (max-width: 768px) {
  #appEditPage {
    padding: 20px 16px;
  }
  
  .edit-container {
    padding: 20px;
  }
  
  .page-header h1 {
    font-size: 24px;
  }
}
</style>
